package com.nidu.demo.oauth2.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.PageQuery;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.oauth2.dto.OAuth2RefreshTokenListQry;
import com.nidu.demo.oauth2.dto.OAuth2RefreshTokenPageQry;
import com.nidu.demo.oauth2.convertor.OAuth2RefreshTokenConvertor;
import com.nidu.demo.oauth2.gateway.OAuth2RefreshTokenGateway;
import com.nidu.demo.oauth2.mapper.OAuth2RefreshTokenMapper;
import com.nidu.demo.oauth2.mapper.dataobject.OAuth2ClientDO;
import com.nidu.demo.oauth2.mapper.dataobject.OAuth2CodeDO;
import com.nidu.demo.oauth2.mapper.dataobject.OAuth2RefreshTokenDO;
import com.nidu.demo.oauth2.model.OAuth2RefreshToken;
import com.nidu.demo.oauth2.model.OAuth2RefreshTokenCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Set;
import java.util.List;

@Component
@RequiredArgsConstructor
public class OAuth2RefreshTokenGatewayImpl implements OAuth2RefreshTokenGateway {

    private final OAuth2RefreshTokenMapper mapper;
    private final OAuth2RefreshTokenConvertor convertor;

    @Override
    public OAuth2RefreshToken create(OAuth2RefreshToken token) {
        OAuth2RefreshTokenDO tokenDO = convertor.toDataObject(token);
        mapper.insert(tokenDO);
        return convertor.toDomainObject(tokenDO);
    }

    @Override
    public OAuth2RefreshToken update(OAuth2RefreshToken token) {
        OAuth2RefreshTokenDO tokenDO = convertor.toDataObject(token);
        mapper.updateById(tokenDO);
        return convertor.toDomainObject(tokenDO);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        mapper.deleteByIds(ids);
    }

    @Override
    public OAuth2RefreshToken getById(Long id) {
        OAuth2RefreshTokenDO tokenDO = mapper.selectById(id);
        if (tokenDO == null) {
            return null;
        }
        return convertor.toDomainObject(tokenDO);
    }

    @Override
    public OAuth2RefreshToken getByRefreshToken(String refreshToken) {
        if (refreshToken == null) {
            return null;
        }
        OAuth2RefreshTokenDO tokenDO = mapper.selectByRefreshToken(refreshToken);
        if (tokenDO == null) {
            return null;
        }
        return convertor.toDomainObject(tokenDO);
    }

    @Override
    public List<OAuth2RefreshToken> listByCondition(OAuth2RefreshTokenCriteria criteria) {
        LambdaQueryWrapper<OAuth2RefreshTokenDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(!CollUtil.isEmpty(criteria.getRefreshTokenIds()), OAuth2RefreshTokenDO::getId, criteria.getRefreshTokenIds());

        wrapper.eq(!StrUtil.isEmpty(criteria.getRefreshToken()), OAuth2RefreshTokenDO::getRefreshToken, criteria.getRefreshToken());
        wrapper.eq(criteria.getClientId() != null, OAuth2RefreshTokenDO::getClientId, criteria.getClientId());
        wrapper.eq(criteria.getUserId() != null, OAuth2RefreshTokenDO::getUserId, criteria.getUserId());
        List<OAuth2RefreshTokenDO> tokenDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(tokenDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(tokenDOS);
    }

    @Override
    public PageResponse<OAuth2RefreshToken> pageByCondition(OAuth2RefreshTokenCriteria criteria) {
        LambdaQueryWrapper<OAuth2RefreshTokenDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(!CollUtil.isEmpty(criteria.getRefreshTokenIds()), OAuth2RefreshTokenDO::getId, criteria.getRefreshTokenIds());

        LocalDateTime[] createTime = criteria.getCreateTime();
        if (createTime != null) {
            if (createTime.length == 1 && createTime[0] != null) {
                wrapper.ge(OAuth2RefreshTokenDO::getCreateTime, createTime[0]);
            } else if (createTime.length > 1 && createTime[0] != null && createTime[1] != null) {
                wrapper.between(OAuth2RefreshTokenDO::getCreateTime, createTime[0], createTime[1]);
            }
        }

        wrapper.eq(!StrUtil.isEmpty(criteria.getRefreshToken()), OAuth2RefreshTokenDO::getRefreshToken, criteria.getRefreshToken());
        wrapper.eq(criteria.getClientId() != null, OAuth2RefreshTokenDO::getClientId, criteria.getClientId());
        wrapper.eq(criteria.getUserId() != null, OAuth2RefreshTokenDO::getUserId, criteria.getUserId());

        // 创建分页对象，确保使用 OAuth2RefreshTokenDO
        Page<OAuth2RefreshTokenDO> page = new Page<>(criteria.getPageIndex(), criteria.getPageSize());

        // 排序字段
        if (!StrUtil.isEmpty(criteria.getOrderBy())) {
            if (PageQuery.DESC.equals(criteria.getOrderDirection())) {
                page.addOrder(OrderItem.desc(criteria.getOrderBy()));
            } else {
                page.addOrder(OrderItem.asc(criteria.getOrderBy()));
            }
        }
        mapper.selectPage(page, wrapper);
        List<OAuth2RefreshToken> tokens = convertor.toDomainObjects(page.getRecords());
        return PageResponse.of(tokens, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }
}